#include <stdio.h>
#include <string.h>

static const char *base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

static void base64_encode(unsigned char * src_str, char *des_str, int src_size)
{
    int i, des_index = 0, index = 0;

    for(i=0; i+2<src_size && src_size/3>0; i=i+3)
    {
        index = src_str[i]>>2;
        des_str[des_index++] = base64_chars[index];

        index = (src_str[i+1]>>4) + (src_str[i]<<4 & 0x30);
        des_str[des_index++] = base64_chars[index];

        index = (src_str[i+1]<<2 & 0x3f) + (src_str[i+2]>>6);
        des_str[des_index++] = base64_chars[index];

        index = src_str[i+2] & 0x3f;
        des_str[des_index++] = base64_chars[index];
    }
    switch (src_size%3) {
        case 0:
            break;
        case 1:
            index = src_str[i]>>2;
            des_str[des_index++] = base64_chars[index];

            index = src_str[i]<<4 & 0x30;
            des_str[des_index++] = base64_chars[index];

            des_str[des_index++] = base64_chars[64];
            des_str[des_index++] = base64_chars[64];
            break;

        case 2:
            index = src_str[i]>>2;
            des_str[des_index++] = base64_chars[index];

            index = (src_str[i+1]>>4) + (src_str[i]<<4 & 0x30);
            des_str[des_index++] = base64_chars[index];

            index = src_str[i+1]<<2 & 0x3f;
            des_str[des_index++] = base64_chars[index];

            des_str[des_index++] = base64_chars[64];
            break;
    }
}

